package com.webwork.lims.warehouse.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.webwork.lims.common.controller.SuperCtrl;
import com.webwork.lims.common.dataobject.CtrlerAndTime;
import com.webwork.lims.orders.dataobject.Order;
import com.webwork.lims.orders.dataobject.OrderStatus;
import com.webwork.lims.orders.service.OrderService;
import com.webwork.lims.stock.service.StockService;
import com.webwork.lims.system.dataobject.User;
import com.webwork.lims.transport.dataobject.TransOrder;
import com.webwork.lims.transport.dataobject.TransStatus;
import com.webwork.lims.transport.dataobject.Ways;
import com.webwork.lims.transport.service.TransService;
import com.webwork.lims.transport.service.WaysService;
import com.webwork.lims.util.DateFormat;
import com.webwork.lims.util.Paging;
import com.webwork.lims.util.StrManager;
import com.webwork.lims.warehouse.dataobject.OutcomeOrder;
import com.webwork.lims.warehouse.dataobject.OutcomeType;
import com.webwork.lims.warehouse.dataobject.WarehouseStatus;
import com.webwork.lims.warehouse.service.OutcomeService;

@Controller
@RequestMapping(value = "/warehouse")
public class OutcomeController extends SuperCtrl {

	@Autowired
	private OutcomeService outcomeSve;
	
	@Autowired
	private OrderService orderSve;
	
	@Autowired
	private TransService transSve;
	
	@Autowired
	private StockService stockSve;
	
	@Autowired
	private WaysService waySve;
	
	@RequestMapping(value = "/outcome")
	@Override
	public String mainPage() {
		return "outcome";
	}
	
	@RequestMapping(value="loadType")
	@ResponseBody
	public ResponseEntity<String> loadType() {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeType[] types = OutcomeType.useableValues();
		List<Object> ret = new ArrayList<Object>();
		for (OutcomeType o : types) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("value", o.getCode());
			map.put("name", o.getCode() + " - " + o.getMsg());
			ret.add(map);
		}
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "queryOutcomeList")
	@ResponseBody
	public ResponseEntity<String> queryList(
			@RequestParam(value = "page") int page,
			@RequestParam(value = "rows") int rows,
			@RequestParam(required = false, value = "cmd") String cmdStr)
					throws Exception {
		OutcomeOrder queryObj = new OutcomeOrder();
		if (!StrManager.isEmpty(cmdStr)) {
			queryObj = new Gson().fromJson(cmdStr, OutcomeOrder.class);
			queryObj.setStatus(queryObj.getStatusCode());
			queryObj.setType(queryObj.getTypeCode());
		}
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Map<String, Object> ret = new HashMap<String, Object>();
	
		ret.put("total", outcomeSve.count(queryObj));
		ret.put("rows", outcomeSve.query(queryObj, new Paging(page, rows)));
		
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "getOutcome")
	@ResponseBody
	public ResponseEntity<String> getOutcome(@RequestParam("outcomeId") String outcomeId) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeOrder order = outcomeSve.get(outcomeId);
		order.setTypeCode(order.getType().getCode());
		return new ResponseEntity<String>(new Gson().toJson(order).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "addOutcome")
	@ResponseBody
	public String addOutcome(@RequestParam("jsonObj") String jsonObj, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeOrder order = new Gson().fromJson(jsonObj, OutcomeOrder.class);
		
		//检查库存
		if (!stockSve.checkStock(order.getSku(), order.getAmount())) {
			return "notEnough";
		}
		
		order.setOutcomeId("OC" + DateFormat.NUMBER.format(new Date()));
		order.setType(order.getTypeCode());
		if (order.getType() == OutcomeType.DELIVERY) {
			return "notAllow";
		}
		order.setStatus(WarehouseStatus.CREATED);
		order.setCreate(new CtrlerAndTime(user.getUserName(), new Date()));
		outcomeSve.save(order);
		return SUCCESS;
	}
	
	@RequestMapping(value = "editOutcome")
	@ResponseBody
	public String editOutcome(@RequestParam("jsonObj") String jsonObj) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeOrder o = new Gson().fromJson(jsonObj, OutcomeOrder.class);
		//检查库存
		if (!stockSve.checkStock(o.getSku(), o.getAmount())) {
			return "notEnough";
		}
		OutcomeOrder order = outcomeSve.get(o.getOutcomeId());
		if (order == null) {
			return NOT_EXIST;
		}
		order.setSku(o.getSku());
		order.setAmount(o.getAmount());
		outcomeSve.save(order);
		return SUCCESS;
	}
	
	@RequestMapping(value = "getBySelf")
	@ResponseBody
	public String getBySelf(@RequestParam("outcomeId") String outcomeId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeOrder order = outcomeSve.get(outcomeId);
		if (order == null) {
			return FAIL;
		}
		//出库扣库存
		String ret = stockSve.useStock(order.getSku(), order.getAmount());
		if (ret.equalsIgnoreCase("notenough")) {
			return "notEnough";
		}
		
		order.setStatus(WarehouseStatus.COMPLETE);
		order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		outcomeSve.save(order);
		
		Order o = orderSve.get(order.getOrderId());
		o.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		o.setStatus(OrderStatus.COMPLETE);
		orderSve.save(o);
		
		return SUCCESS;
	}
	
	@RequestMapping(value = "outcomeOrder")
	@ResponseBody
	public String OutcomeOrder(@RequestParam("outcomeId") String outcomeId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeOrder order = outcomeSve.get(outcomeId);
		if (order == null) {
			return FAIL;
		}
		Order o = null;
		String wayLine = "";
		if (!StrManager.isEmpty(order.getOrderId())) {
			o = orderSve.get(order.getOrderId());
			wayLine = transSve.getWayLine(o.getZoneCode());
			if (StrManager.isEmpty(wayLine)) {
				return "notLine";
			}
		}
		//出库扣库存
		String ret = stockSve.useStock(order.getSku(), order.getAmount());
		if (ret.equalsIgnoreCase("notenough")) {
			return "notEnough";
		}
		
		order.setStatus(WarehouseStatus.COMPLETE);
		order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		outcomeSve.save(order);
		
		//生成配送单
		if (order.getType() == OutcomeType.DELIVERY) {
			TransOrder trans = new TransOrder();
			trans.setTransId("T" + DateFormat.NUMBER.format(new Date()));
			int hours = 0;
			String[] zones = wayLine.split("-");
			for (int i = 0; i < zones.length; i++) {
				int j = i + 1;
				if (j < zones.length) {
					Ways queryObj = new Ways();
					queryObj.setStartCode(Integer.valueOf(zones[i]));
					queryObj.setEndCode(Integer.valueOf(zones[j]));
					List<Ways> ways = waySve.query(queryObj);
					if (ways != null && ways.size() > 0) {
						hours += ways.get(0).getHour();
					}
				}
			}
			trans.setWayLine(wayLine);
			trans.setHours(hours);
			trans.setCreate(new CtrlerAndTime(user.getUserName(), new Date()));
			trans.setStatus(TransStatus.WAITING);
			transSve.save(trans);
			
			o.setTransId(trans.getTransId());
			orderSve.save(o);
		}
		return SUCCESS;
	}
	
	@RequestMapping(value = "cancelOutcome")
	@ResponseBody
	public String cancelOrder(@RequestParam("outcomeId") String outcomeId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OutcomeOrder order = outcomeSve.get(outcomeId);
		if (order == null) {
			return FAIL;
		}
		order.setStatus(WarehouseStatus.CANCEL);
		order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		outcomeSve.save(order);
		
		if (!StrManager.isEmpty(order.getOrderId())) {
			Order o = orderSve.get(order.getOrderId());
			o.setStatus(OrderStatus.CANCEL);
			o.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
			orderSve.save(o);
		}
		return SUCCESS;
	}
	
}
